package org.example.netty.mgt;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import org.example.netty.model.ExtendedChannelContext;
import org.example.netty.config.NettyEndpointConfig;
import org.example.netty.utils.SnowflakeIdGenerator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ClientConnectionManager implements ConnectionManager{
    private final SnowflakeIdGenerator snowflakeIdGenerator;
    private ExtendedChannelContext channelContext;
    private NettyEndpointConfig config;

    public ClientConnectionManager(NettyEndpointConfig config) throws NettyEndpointConfig.ValueIsEmpty {
        this.config=config;
        if (config.getMachineId()!=0){
            this.snowflakeIdGenerator = new SnowflakeIdGenerator(config.getMachineId());
        }else {
            throw new NettyEndpointConfig.ValueIsEmpty("machineId不能为空");
        }
    }

    @Override
    public long generateRequestId() {
        return snowflakeIdGenerator.nextId();
    }

    @Override
    public NettyEndpointConfig getNettyConfig() {
        return config;
    }

    @Override
    public void putChannel(Channel channel) {
        channelContext = new ExtendedChannelContext(channel);
    }

    @Override
    public void removeChannel(Channel channel) {
        if (channelContext==null){
            return;
        }
        channelContext.close();
        channelContext = null;
    }

    @Override
    public Channel getChannel(ChannelId channelId) {
        if (channelContext==null){
            return null;
        }
        return channelContext.getChannel();
    }


    @Override
    public ExtendedChannelContext getExtendedChannelContext(ChannelId channelId) {
        return channelContext;
    }

    @Override
    public List<ExtendedChannelContext> getAllExtendedChannelContext() {
        return new ArrayList<>(Arrays.asList(channelContext));
    }
}
